<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col :span="8">
          <el-button type="primary" @click="addrolesDialog">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList" style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 多个类用数组 -->
            <el-row :class="['bdbottom', i == 0 ? 'bdtop' : '', 'venter']" v-for="(item1, i) in scope.row.children" :key="item1.id">
              <!-- 渲染一级 -->
              <el-col :span="5">
                <el-tag closable @close="remove(scope.row, item1.id)"> {{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级跟三级 -->
              <el-col :span="19">
                <el-row v-for="(item2, i2) in item1.children" :key="item2.id" :class="[i2 == 0 ? '' : 'bdtop', 'venter']">
                  <!-- 二级 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="remove(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag type="warning" closable @close="remove(scope.row, item3.id)" v-for="item3 in item2.children" :key="item3.id">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-search" @click="editRoles(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeRoles(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showsetdialogVisible(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 点击添加角色  打开模态框 -->
    <el-dialog title="添加用户" :visible.sync="rolesDialog" width="50%" @close="rolesDialogClose">
      <el-form :model="rolesForm" :rules="rolesRules" ref="rolesFormRef" label-width="100px">
        <!-- 用户名称 -->
        <el-form-item label="用户名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <!-- 用户描述 -->
        <el-form-item label="用户描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击编辑角色  打开模态框 -->
    <el-dialog title="编辑用户" :visible.sync="editrolesDialog" width="50%" @close="editrolesDialogClose">
      <el-form :model="editrolesForm" :rules="rolesRules" ref="editrolesFormRef">
        <!-- 用户名称 -->
        <el-form-item label="用户名称" prop="roleName">
          <el-input v-model="editrolesForm.roleName"></el-input>
        </el-form-item>
        <!-- 用户描述 -->
        <el-form-item label="用户描述" prop="roleDesc">
          <el-input v-model="editrolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editrolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="addeditrolesDialog">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="setdialogVisible" width="50%">
      <!-- 树性控件 -->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="keysTree" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //保存正在操作的角色id
      roleId: '',
      // 分配权限
      setdialogVisible: false,
      // 树形数据
      treeProps: {
        // 要绑定的名称
        label: 'authName',
        // 父级节点嵌套
        children: 'children'
      },
      keysTree: [],
      // 所有角色数据列表
      rolesList: [],
      //权限树数据
      rightsList: [],

      //   控制模态款
      rolesDialog: false,
      //   编辑
      editrolesDialog: false,
      //   添加用户
      rolesForm: {
        roleName: '',
        roleDesc: ''
      },
      //   编辑按钮
      editrolesForm: {},
      //   校验
      rolesRules: {
        roleName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入用户描述', trigger: 'blur' },
          { min: 3, message: '不少于3个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //获取所有角色列表
    async getRolesList() {
      const { data: res } = await this.$axios.get('roles')
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error('数据请求失败')
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 点击添加按钮  打开模态
    addrolesDialog() {
      this.rolesDialog = true
    },
    // 关闭dialog回调
    rolesDialogClose() {
      // 让单前的表单清空
      this.$refs.rolesFormRef.resetFields()
    },

    // 点击确认按钮
    addUserInfo() {
      // 表单校验成功才继续执行下面
      this.$refs.rolesFormRef.validate(async val => {
        // console.log(val)
        if (!val) return
        const { data: res } = await this.$axios.post('roles', this.rolesForm)

        //    如果不为201 则代表失败
        if (res.meta.status !== 201) return this.$message.error('添加数据失败')
        this.$message.success('创建成功')
        // 刷新数据
        this.getRolesList()
        // 面板关闭
        this.rolesDialog = false
      })
    },
    // 点击编辑
    async editRoles(id) {
      //   console.log(id)
      // 打开dialog
      this.editrolesDialog = true
      //   根据id查询角色
      const { data: res } = await this.$axios.get('roles/' + id, { id })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('查询失败')
      this.editrolesForm = res.data
      // console.log(this.editrolesForm)
    },
    // 编辑的dia
    editrolesDialogClose() {
      this.$refs.editrolesFormRef.resetFields()
    },
    // 编辑的确定按钮
    addeditrolesDialog() {
      this.$refs.editrolesFormRef.validate(async val => {
        if (!val) return

        const { data: res } = await this.$axios.put('roles/' + this.editrolesForm.roleId, this.editrolesForm)

        if (res.meta.status !== 200) return this.$message.error('编辑出错')
        this.$message.success('提交成功')
        //  关闭dia
        this.editrolesDialog = false
        // 刷新数据
        this.getRolesList()
      })
    },
    // 点击删除按钮
    async removeRoles(id) {
      const removeConfirm = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeConfirm == 'cancel') return this.$message.info('以取消删除')
      const { data: res } = await this.$axios.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除出错')
      this.$message.success('删除成功')
      //  刷新数据
      this.getRolesList()
      // console.log(removeConfirm)
    },
    // 点击三级列表提示
    async remove(roleId, rightId) {
      const removeConfirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(roleId, rightId, removeConfirm)

      if (removeConfirm === 'cancel') return this.$message.info('删除取消成功')
      const { data: res } = await this.$axios.delete(`roles/${roleId.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('取消权限失败')
      this.$message.success('权限删除成功')
      //  不能直接刷新数据
      // this.getRolesList()
      // 让最新的数据复制回去
      roleId.children = res.data
    },
    // 点击权限按钮打开
    async showsetdialogVisible(role) {
      //将role.id保存起来以供保存权限时使用
      this.roleId = role.id
      //当点击分配权限按钮时，展示对应的对话框
      this.setdialogVisible = true
      //获取所有权限的数据
      const { data: res } = await this.$axios.get('rights/tree')
      //如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) return this.$message.error('获取权限树失败')
      //如果返回状态正常，将请求的数据保存在data中
      this.rightsList = res.data
      // console.log(this.rightsList)

      //调用getLeafKeys进行递归，将三级权限添加到数组中
      // console.log(role)
      // 每次点击先让数组清空
      this.keysTree = []
      this.getLeafKeys(role, this.keysTree)

      // console.log(this.keysTree)
    },
    getLeafKeys(node, arr) {
      //该函数会获取到当前角色的所有三级权限id并添加到defKeys中
      //如果当前节点不包含children属性，则表示node为三级权限

      if (!node.children) {
        return arr.push(node.id)
      }
      //递归调用
      node.children.forEach(item => this.getLeafKeys(item, arr))

      // console.log(arr)
    },
    // 为角色添加分配权限
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      // console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$axios.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      this.setdialogVisible = false
      this.getRolesList()
    }
  }
}
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.venter {
  display: flex;
  align-items: center;
}
</style>
